import time
import logging
import traceback

from utils.threadpool import async_thread, get_thread_pool
from utils.utils import timing_decorator

logger = logging.getLogger(__name__)

# 模拟发送邮件
def send_email(subject, content, to_addr):
    logger.info(f"发送邮件中... subject={subject}")
    # TODO 模拟发邮件耗时
    time.sleep(1)
    logger.info("邮件发送成功...")

# 异步执行的函数
@async_thread
def async_print():
    print('开始 async_print.......')
    time.sleep(3)
    print('结束 async_print.......')


def delay_work1(name):
    print(f'delay_work1 start...{name}')
    time.sleep(2)
    print(f'delay_work1 end.....{name}')

    return f'{name}-1'


def delay_work2(name):
    print(f'delay_work2 start...{name}')
    time.sleep(3)
    print(f'delay_work2 end.....{name}')

    return f'{name}-2'


def delay_work3(name):
    print(f'delay_work3 start...{name}')
    time.sleep(4)
    print(f'delay_work3 end.....{name}')

    return f'{name}-3'


@timing_decorator
def biz_async_works(name):
    # 初始化线程池
    thread_pool = get_thread_pool()

    # async_submit
    future1 = thread_pool.submit(delay_work1, name)
    future2 = thread_pool.submit(delay_work2, name)
    future3 = thread_pool.submit(delay_work3, name)

    # sync wait
    try:
        ret_name1 = future1.result()
        ret_name2 = future2.result()
        ret_name3 = future3.result()
    except Exception as e:
        logger.error(f'并发执行async_works有异常: {traceback.format_exc()}')
        return ''

    return f'{ret_name1} - {ret_name2} - {ret_name3}'
